<?php
/**
 * 用于处理概率抽奖类
 *
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: dpLottery.php 1 2012-04-10 14:41:54Z Mo.yi $
 * @package db
 * @since 1.0
 */

class dpLottery
{
	/**
	 * 奖品数据
	 * 数组key：id(奖品ID)，name(奖品名称)，probability(中奖机率)
	 */
	private $_prize = array();

	/**
	 * 构造方法
	 * @param array $prize 奖品数组
	 */
	public function __construct($prize)
	{
		$this->_prize = $prize;
	}

	/**
	 * 计算概率方法
	 */
	private function _calculateProbability(&$data)
	{
		$result = '';

	    $probabilityNum = array_sum($data); 

	    foreach ($data as $key => $cur) { 
	        $randNum = mt_rand(1, $probabilityNum); 
	        if ($randNum <= $cur) { 
	            $result = $key; 
	            break; 
	        } else { 
	            $probabilityNum -= $cur; 
	        } 
	    }
	    unset($data);
	    return $result;
	}

	/**
	 * 获取中奖结果
	 */
	public function getWinningResult()
	{
		if (empty($this->_prize)) {
			return false;
		}

		$data  = array();
		$prize = array();
		foreach ($this->_prize as $key => $value) {
			$data[$value['id']]  = $value['probability'];
			$prize[$value['id']] = $value['name'];
		}

		$prize_id = $this->_calculateProbability($data);

		return array('id'=>$prize_id , 'name'=>$prize[$prize_id]);
	}


}
?>